import XYZ from 'ol/source/XYZ'
import Feature from 'ol/Feature'
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import { Point } from 'ol/geom'
import { Fill, Stroke, Style, Text, Icon } from 'ol/style'
import Overlay from 'ol/Overlay'
// import WKT from 'ol/format/WKT'
import { GeoJSON } from 'ol/format'
import { chinaGeoJSON } from '@/api/constant'
// 初始化图层
export const initLayer = (map, type = 'xzqh') => {
  const wxtTdtLayer = new TileLayer({
    name: '影像图',
    layerId: 'wxt',
    type: 'base',
    source: new XYZ({
      crossOrigin: 'anonymous',
      url: 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'
    })
  })
  const xzqhTdtLayer = new TileLayer({
    name: '行政区划',
    layerId: 'xzqh',
    type: 'base',
    source: new XYZ({
      crossOrigin: 'anonymous',
      url: 'https://t{0-6}.tianditu.gov.cn/DataServer?T=vec_w&l={z}&tk=bc151140e4136fa04f85e3df8bdba119&x={x}&y={y}'
    })
  })
  const dxtTdtLayer = new TileLayer({
    name: '地形图',
    layerId: 'dxt',
    type: 'base',
    source: new XYZ({
      crossOrigin: 'anonymous',
      url: 'https://t{0-6}.tianditu.gov.cn/DataServer?T=ter_w&l={z}&tk=bc151140e4136fa04f85e3df8bdba119&x={x}&y={y}'
    })
  })
  // 添加注记
  // const textTdtLayer = new TileLayer({
  //   name: '注记',
  //   layerId: 'text',
  //   source: new XYZ({
  //     crossOrigin: 'anonymous',
  //     url: 'http://t{0-6}.tianditu.gov.cn/DataServer?T=cva_w&tk=bc151140e4136fa04f85e3df8bdba119&x={x}&y={y}&l={z}'
  //   })
  // })
  map.addLayer(wxtTdtLayer)
  map.addLayer(xzqhTdtLayer)
  map.addLayer(dxtTdtLayer)
  // map.addLayer(textTdtLayer)

  const layers = map.getLayers().getArray()
  layers.forEach((e) => {
    if (e.get('layerId') === type) {
      e.setVisible(true)
    } else if (e.get('layerId') === 'text') {
      e.setVisible(true)
    } else {
      e.setVisible(false)
    }
  })
}

/**
 * 缩小
 */
export const zoomOut = (map) => {
  const view = map.getView()
  const zoom = view.getZoom()
  view.setZoom(zoom - 1)
}
/**
 * 放大
 */
export const zoomIn = (map) => {
  const view = map.getView()
  const zoom = view.getZoom()
  view.setZoom(zoom + 1)
}

/**
 * 设置地图中心点及级别
 * @param {Object} map
 * @param {Array} point ['123.23','32.232']
 * @param {*} zoom  8
 */
export const setMapCenter = (map, point, zoom) => {
  const zoomNum = zoom
  map.getView().animate({
    center: point,
    zoom: zoomNum
  })
}

/**
 * 绘制点位方法
 * @param {*} map 地图对象
 * @param {*} pointItem 点位经纬度
 * @param {*} item 点位所有数据
 * @param {*} layerId 图层id
 */
export const drawPoint = (map, pointItem, item, type, layerId, zIndex = 99) => {
  const point = new Feature({
    geometry: new Point(pointItem),
    type: 'point'
  })
  const iconStyle = new Style({
    image: new Icon({
      scale: byTypeGetIcon(item, type).scale || 1,
      displacement: [0, 0],
      src: byTypeGetIcon(item, type).img
    }),
    text: new Text({
      font: '12px Arial',
      text: item.aqi ? item.aqi + '' : '',
      placement: 'point',
      textAlign: 'center',
      offsetY: -3
    })
  })
  point.setStyle(iconStyle)
  var PointSource = new VectorSource({ wrapX: true })
  PointSource.addFeature(point)
  const PointLayer = new VectorLayer({
    attr: item,
    name: 'pointer',
    layerId: layerId,
    zIndex: zIndex || 99,
    source: PointSource
  })
  map.addLayer(PointLayer)
}

// 删除行政区
export const deleteCity = (map, name) => {
  const layers = map.getLayers().getArray()
  for (let i = layers.length - 1; i >= 0; i--) {
    const layer = layers[i]
    const layerId = layer.get('layerId')
    if (layerId === name) {
      layer.getSource().clear()
      map.removeLayer(layer)
    }
  }
}

// 平移到执行位置
export const panTo = (map, feature, maxZoom = 12) => {
  const view = map.getView()
  view.fit(feature.getGeometry(), {
    padding: [0, 0, 0, 0],
    maxZoom
  })
}

// 添加提示框
export const addWindowTip = (map, coordinate, info) => {
  const layer = map.getOverlayById('pointTip')
  if (layer) {
    map.removeOverlay(layer)
  }
  var container = document.createElement('div')
  container.className = 'ol-popup'
  container.id = 'popup'
  const overlay = new Overlay({
    id: 'pointTip',
    element: container,
    autoPan: true
  })
  container.innerHTML = ` <div id="popup-content" class="ol-content">${info}</div>`
  map.addOverlay(overlay)
  overlay.setPosition(coordinate)
}

/**
 * 设置中心点
 * @param {Object} map 地图对象
 * @param {Array} coord [123.23,34.3423]
 * @param {Number} zoom 10
 */
export const zoomToCenter = (map, coord, zoom = 10) => {
  const view = map.getView()
  view.setZoom(zoom)
  view.setCenter(coord)
}

// 设置点位样式
function byTypeGetIcon(item, type) {
  let img = ''
  let scale = 1
  let imgW = 0
  let imgH = 0
  if (type === 'company') {
    imgW = 30
    imgH = 30
    scale = 0.8
    if (item.alarmLevel === '紧急报警') {
      img = require('@/assets/images/mapIcon/tp4.png')
    } else if (item.alarmLevel === '重要报警') {
      img = require('@/assets/images/mapIcon/tp3.png')
    } else if (item.alarmLevel === '一般报警') {
      img = require('@/assets/images/mapIcon/tp2.png')
    } else if (item.alarmLevel === '无报警') {
      img = require('@/assets/images/mapIcon/tp1.png')
    } else if (item.alarmLevel === '未接入') {
      img = require('@/assets/images/mapIcon/tp0.png')
    }
    switch (item.type) {
      case '特品企业':
        if (item.alarmLevel === '紧急报警') {
          img = require('@/assets/images/mapIcon/tp4.png')
        } else if (item.alarmLevel === '重要报警') {
          img = require('@/assets/images/mapIcon/tp3.png')
        } else if (item.alarmLevel === '一般报警') {
          img = require('@/assets/images/mapIcon/tp2.png')
        } else if (item.alarmLevel === '无报警') {
          img = require('@/assets/images/mapIcon/tp1.png')
        } else if (item.alarmLevel === '未接入') {
          img = require('@/assets/images/mapIcon/tp0.png')
        }
        break
      case '民品企业':
        if (item.alarmLevel === '紧急报警') {
          img = require('@/assets/images/mapIcon/mp4.png')
        } else if (item.alarmLevel === '重要报警') {
          img = require('@/assets/images/mapIcon/mp3.png')
        } else if (item.alarmLevel === '一般报警') {
          img = require('@/assets/images/mapIcon/mp2.png')
        } else if (item.alarmLevel === '无报警') {
          img = require('@/assets/images/mapIcon/mp1.png')
        } else if (item.alarmLevel === '未接入') {
          img = require('@/assets/images/mapIcon/mp0.png')
        } else if (item.alarmLevel === '分区') {
          img = require('@/assets/images/mapIcon/w1.png')
        }
        break
      case '其他企业':
      case '其他':
        if (item.alarmLevel === '紧急报警') {
          img = require('@/assets/images/mapIcon/qt4.png')
        } else if (item.alarmLevel === '重要报警') {
          img = require('@/assets/images/mapIcon/qt3.png')
        } else if (item.alarmLevel === '一般报警') {
          img = require('@/assets/images/mapIcon/qt2.png')
        } else if (item.alarmLevel === '无报警') {
          img = require('@/assets/images/mapIcon/qt1.png')
        } else if (item.alarmLevel === '未接入') {
          img = require('@/assets/images/mapIcon/qt0.png')
        }
        break
    }
  } else {
    if (item === 'center') {
      img = require('@/assets/images/map/circleCenterIco.png')
    }
  }

  return { img, imgW, imgH, scale }
}

export const clipLayer = (map) => {
  // const result = chinaGeoJSON.features
  // 加边框
  const styles = new Style({
    stroke: new Stroke({
      color: '#199aec',
      width: 2
    }),
    fill: new Fill({
      color: 'rgba(255, 0, 255, 1)'
    })
  })
  const features = new GeoJSON({ featureProjection: 'EPSG:4326' }).readFeatures(chinaGeoJSON)
  const vectorSource = new VectorSource({
    features
  })
  const vector = new VectorLayer({
    source: vectorSource,
    style: styles
  })
  map.addLayer(vector)
}